/**
 * Copyright (c) 2011 ~ 2014 Deepin, Inc.
 *               2013 ~ 2014 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

#include <stdlib.h>
#include <string.h>

#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#include <X11/extensions/XInput.h>
#include "common.h"

DeviceInfo *get_device_info_list (int *num)
{
	gdk_init(NULL, NULL);
	if (num == NULL) {
		return NULL;
	}

	int n_devices;
	XDeviceInfo *infos = XListInputDevices(
	                         GDK_DISPLAY_XDISPLAY(gdk_display_get_default()),
	                         &n_devices);
	if (infos == NULL) {
		return NULL;
	}

	int i;
	int j = 0;
	DeviceInfo *list = NULL;
	for (i =0; i< n_devices; i++) {
		if (infos[i].use != IsXExtensionPointer ||
		        infos[i].type < 1 ) {
			continue;
		}

		DeviceInfo *tmp = calloc(j+1, sizeof(DeviceInfo));
		if (tmp == NULL) {
			free(list);
			list = NULL;
			break;
		}

		if (j != 0) {
			memcpy(tmp, list, j * sizeof(DeviceInfo));
			free(list);
			list = NULL;
		}

		tmp[j].name = infos[i].name;
		tmp[j].Atom_name = gdk_x11_get_xatom_name(infos[i].type);
		tmp[j].Xid = infos[i].id;
		tmp[j].Atom = infos[i].type;

		list = tmp;
		j++;
	}

	XFreeDeviceList(infos);

	/*if (list != NULL) {*/
		/*for (i = 0; i< j; i++) {*/
			/*printf("Xid: %d\n", list[i].Xid);*/
			/*printf("Atom: %d\n", list[i].Atom);*/
			/*printf("Name: %s\n", list[i].Name);*/
			/*printf("Atom Name: %s\n", list[i].Atom_name);*/
		/*}*/
	/*}*/

	*num = j;
	return list;
}

/*
int main()
{
	int n = 0;
	DeviceInfo *l = get_device_info_list(&n);
	if (l == NULL) {
		return -1;
	}

	free(l);

	return 0;
}
*/
